import {login,loginOut} from 'api/user'
import {getUserInfo} from '../../utils/auth'

const user={
    state:{
        user:getUserInfo()
    },
    mutations:{
        SET_USER:(state,user)=>{
            state.user=user;
            try{
                window.localStorage.setItem('userInfo', JSON.stringify(user));
              }catch(e){

            } 
        }
    },
    actions:{
        // 登录
        loginByUsername({commit},userInfo){
            const username=userInfo.username.trim();
            return new Promise((resolve,reject)=>{
                login(username,userInfo.password).then(res=>{
                    if(res.data.error==0){
                        commit('SET_USER', res.data.content);
                        resolve();
                    }else{
                        reject();
                    }
                })
            })
        },
        //登出
        loginOut({commit}){
            return new Promise((resolve,reject)=>{
                loginOut().then((res)=>{
                    if(res.data.error==0){
                        commit('SET_USER', '');
                        resolve();
                    }else{
                        reject();
                    }
                })
            })
        }
    }   
}

export default user